package cn.itcast.web.controller.cargo;

import cn.itcast.dao.cargo.PackingListDao;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.PackingList;
import cn.itcast.domain.cargo.ShippingOrder;
import cn.itcast.domain.cargo.ShippingOrderExample;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.service.cargo.ShippingOrderService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import java.io.InputStream;
import java.util.*;


@Controller
@RequestMapping("/cargo/shipping")
@Slf4j
public class ShippingController extends BaseController{
   @Reference
    private ShippingOrderService shippingOrderService;
   @Reference
   private PackingService packingService;
   @Reference
   private ExportService exportService;
   @Autowired
   private PackingListDao packingListDao;
    //1.生成委托单
    @RequestMapping("/add")
    public String shippingAdd(String id){
        //根据id查询装箱单对象
        PackingList packingList = packingService.findBypackingId(id);
        //装箱单对象获取报运ids
        String exportIds = packingList.getExportIds();
        //根据逗号分割ids
        String[] split = exportIds.split(",");
        //根据 分割出来的id  一个个去查询export 并且把获得的对象拼接
        ShippingOrder shippingOrder = new ShippingOrder();
        shippingOrder.setShippingOrderId(id);
        shippingOrder.setMarks(packingList.getMarks());
        String LcNos ="";
        for (String exportId : split) {
            Export export = exportService.findById(exportId);
            shippingOrder.setPortOfLoading(export.getShipmentPort());
            shippingOrder.setPortOfDischar(export.getDestinationPort());
            LcNos += export.getLcno();
        }
        shippingOrder.setLcNo(LcNos);
        //set进shippingOrder对象放在请求域
        request.setAttribute("shipping",shippingOrder);
        return "/cargo/shipping/shipping-add02";
    }

    @RequestMapping("/list")
    public String contractList(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行查询委托单列表:");

        ShippingOrderExample example = new ShippingOrderExample();
        example.setOrderByClause("create_time desc");
        PageInfo<ShippingOrder> pageInfo = shippingOrderService.findByPage(example, pageNum, pageSize);

        request.setAttribute("pageInfo", pageInfo);
        return "cargo/shipping/shipping-list";
    }

    @RequestMapping("/edit")
    public String edit(ShippingOrder shipping){
        shipping.setCreateDept(getLoginUser().getDeptName());
        shipping.setCreateTime(new Date());
        shipping.setCopyNum("1");
        shipping.setSpecialConditio("无");
        shippingOrderService.save(shipping);

        return "redirect:/cargo/packing/list";
    }

    @RequestMapping("/delete")
    public String delete(String id){
        shippingOrderService.deleteByPrimaryKey(id);
        return "redirect:/cargo/shipping/list";
    }

    /**
     * PDF导出（4）填充数据 B 数据源填充 JavaBean填充
     */
    @RequestMapping("/exportPdf")
    public void exportPdf(String id) throws Exception {
        //根据id查询装箱对象
        PackingList packingList = packingListDao.selectByPrimaryKey(id);
        //1. 获取pdf模板文件流
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/shipping.jasper");
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        //查询一个委托单对象
        ShippingOrder shippingOrder = shippingOrderService.selectByPrimaryKey(id);
        //封装
        map.put("shippingOrderId",shippingOrder.getShippingOrderId());
        map.put("orderType",shippingOrder.getOrderType());
        map.put("shipper",shippingOrder.getShipper());
        map.put("consignee",shippingOrder.getConsignee());
        map.put("notifyParty",shippingOrder.getNotifyParty());
        map.put("lcNo",shippingOrder.getLcNo());
        map.put("portOfLoading",shippingOrder.getPortOfLoading());
        map.put("portOfTrans",shippingOrder.getPortOfTrans());
        map.put("portOfDischarge",shippingOrder.getPortOfDischar());
        map.put("isBatch",shippingOrder.getIsBatch());
        map.put("isTrans",shippingOrder.getIsTrans());
        map.put("remark",shippingOrder.getRemark());
        map.put("state",shippingOrder.getState());
        map.put("createTime",new Date());
        map.put("invoiceNo","PIo454asd5555");
        map.put("loadingDate",packingList.getPackingTime());//装期
        map.put("limitDate",shippingOrder.getLimitDate());
        map.put("copyNum",shippingOrder.getCopyNum());
        map.put("marks",shippingOrder.getMarks());
        map.put("descriptions",packingList.getDescriptions()+"");
        map.put("grossWeight",packingList.getGrossWeights()+"");
        map.put("specialConditio",shippingOrder.getSpecialConditio());
        list.add(map);


        // 创建javabena数据源对象
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        //2. 创建JasperPrint对象，用于往模板中填充数据
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in,null,dataSource);
        response.setHeader("content-disposition","attachment;fileName=shipping.pdf");
        ServletOutputStream out = response.getOutputStream();
        //3. 导出PDF
        JasperExportManager.exportReportToPdfStream(jasperPrint,out);
        out.close();
    }
}
